﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using System.Windows.Forms.DataVisualization.Charting;
using Tireguit.Nmon.UI.Elements.Logical;

using System.Drawing.Printing;

namespace Tireguit.Nmon.UI.Elements.Controls
{
    public partial class PlotControl : UserControl
    {
        protected ILog _log = LogManager.GetLogger(typeof(PlotControl));
        protected bool quietopened = false;
        protected System.Windows.Forms.DataVisualization.Charting.Chart Chart1;
        protected SortedDictionary<string, System.Windows.Forms.DataVisualization.Charting.Series> _SeriesList =
            new SortedDictionary<string, System.Windows.Forms.DataVisualization.Charting.Series>();
        protected System.Windows.Forms.DataVisualization.Charting.Legend legend1;

        public IDbConnection Connection { get; protected set; }
        protected Font m_LabelFont = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
        protected Color m_ChartAreaBackColor = System.Drawing.Color.Transparent;
        protected System.Windows.Forms.DataVisualization.Charting.GradientStyle m_ChartAreaBackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.None;
        protected Color m_ChartAreaBackSecondaryColor = System.Drawing.Color.White;
        protected Color m_ChartAreaBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
        protected Color m_ChartAreaShadowColor = System.Drawing.Color.Transparent;

        protected Font m_LegendFont = new System.Drawing.Font("Trebuchet MS", 8F, System.Drawing.FontStyle.Bold);
        protected Font m_LegendTitleFont = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Bold);
        protected Color m_LegendBackColor = System.Drawing.Color.Transparent;
        protected Color m_LegendHeaderSeparatorColor = Color.Gray;
        protected Color m_LegendHeaderBackColor = Color.WhiteSmoke;
        protected bool m_AddLegend = true;

        internal PlotElement _plotElement;
        protected PlotSqlElements _plotsqlElement;
        protected DateTime _startdate;
        public DateTime StartDate 
        { 
            get { return _startdate; }
            set { _startdate = value; _plotsqlElement.StartDate = _startdate; }
        }
        protected DateTime _enddate;
        public DateTime EndDate
        { 
            get { return _enddate; }
            set { _enddate = value; _plotsqlElement.EndDate = _enddate; }
        }


        public PlotControl(IDbConnection connection,DateTime startdate,DateTime enddate)
        {
            Connection = connection;
            InitializeComponent();
            _plotElement = new PlotElement(Connection);
            _plotsqlElement = new PlotSqlElements(Connection);
            StartDate = startdate;
            EndDate = enddate;
        }
        protected bool QuietOpen()
        {
            try
            {
                _log.Debug("start QuietOpen");
                if (Connection.State == ConnectionState.Open)
                {
                    return true;
                }
                Connection.Open();
                quietopened = true;
                return true;
            }
            catch (System.Exception ex)
            {
                _log.Error("QuietOpen", ex);
                return false;
            }
            finally
            {
                _log.Debug("stop QuietOpen");
            }
        }
        protected bool QuietClose()
        {
            try
            {
                _log.Debug("start QuietClose");
                if (!quietopened)
                {
                    return true;
                }
                if (Connection.State == ConnectionState.Closed)
                {
                    return true;
                }
                Connection.Close();
                quietopened = false;
                return true;
            }
            catch (System.Exception ex)
            {
                _log.Error("QuietClose", ex);
                return false;
            }
            finally
            {
                _log.Debug("stop QuietClose");
            }

        }
        #region Init Chart Area
        void InitChartArea(ChartArea chartArea1)
        {
            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.IsClustered = true;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.Perspective = 10;
            chartArea1.Area3DStyle.Rotation = 10;
            chartArea1.Area3DStyle.WallWidth = 0;
           chartArea1.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
            chartArea1.AxisX.IsLabelAutoFit = false;
           chartArea1.AxisX.LabelStyle.Font = m_LabelFont;
            chartArea1.AxisX.LabelStyle.Format = "T";
           // chartArea1.AxisX.LabelStyle.Interval = 20;
            //chartArea1.AxisX.LabelStyle.Enabled = true;
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorTickMark.Size = 2F;
            
            chartArea1.AxisY.IsLabelAutoFit = false;
            chartArea1.AxisY.IsStartedFromZero = false;
            chartArea1.AxisY.LabelStyle.Font = m_LabelFont;
            chartArea1.AxisY.LabelStyle.Format = "N0";
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = m_ChartAreaBackColor;
            chartArea1.BackGradientStyle = m_ChartAreaBackGradientStyle;
            chartArea1.BackSecondaryColor = m_ChartAreaBackSecondaryColor;
            chartArea1.BorderColor = m_ChartAreaBorderColor;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = m_ChartAreaShadowColor;

        }
        #endregion
        #region Legends
        void SetLegends()
        {
            legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            legend1.Alignment = System.Drawing.StringAlignment.Center;
            legend1.IsTextAutoFit = false;
            legend1.BackColor = m_LegendBackColor;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Bottom;
            legend1.Font = m_LegendFont;
            legend1.Name = "Default";
            legend1.TableStyle = System.Windows.Forms.DataVisualization.Charting.LegendTableStyle.Tall;
            legend1.TitleFont = m_LegendTitleFont;
            this.Chart1.Legends.Add(legend1);

            // Add header separator of type line
            Chart1.Legends["Default"].HeaderSeparator = LegendSeparatorStyle.Line;
            Chart1.Legends["Default"].HeaderSeparatorColor = m_LegendHeaderSeparatorColor;

            // Add Color column
            LegendCellColumn firstColumn = new LegendCellColumn();
            firstColumn.ColumnType = LegendCellColumnType.SeriesSymbol;
            firstColumn.HeaderText = "Couleur";
            firstColumn.HeaderBackColor = m_LegendHeaderBackColor;
            Chart1.Legends["Default"].CellColumns.Add(firstColumn);

            // Add Legend Text column
            LegendCellColumn secondColumn = new LegendCellColumn();
            secondColumn.ColumnType = LegendCellColumnType.Text;
            secondColumn.HeaderText = "Nom";
            secondColumn.Text = "#LEGENDTEXT";
            secondColumn.HeaderBackColor = m_LegendHeaderBackColor;
            Chart1.Legends["Default"].CellColumns.Add(secondColumn);

            // Add AVG cell column
            LegendCellColumn avgColumn = new LegendCellColumn();
            avgColumn.Text = "#AVG{N2}";
            avgColumn.HeaderText = "Moy";
            avgColumn.Name = "AvgColumn";
            avgColumn.HeaderBackColor = m_LegendHeaderBackColor;
            Chart1.Legends["Default"].CellColumns.Add(avgColumn);

            // Add Total cell column
            LegendCellColumn totalColumn = new LegendCellColumn();
            totalColumn.Text = "#MAX{N1}";
            totalColumn.HeaderText = "Max";
            totalColumn.Name = "TotalColumn";
            totalColumn.HeaderBackColor = m_LegendHeaderBackColor;
            Chart1.Legends["Default"].CellColumns.Add(totalColumn);

            // Set Min cell column attributes
            LegendCellColumn minColumn = new LegendCellColumn();
            minColumn.Text = "#MIN{N1}";
            minColumn.HeaderText = "Min";
            minColumn.Name = "MinColumn";
            minColumn.HeaderBackColor = m_LegendHeaderBackColor;
            Chart1.Legends["Default"].CellColumns.Add(minColumn);
        }
        #endregion
        protected void InitSerie(string name, System.Collections.IEnumerable enumerable,string champX,string champY)
        {
            InitSerie(name);
            Chart1.Series[name].Points.DataBindXY(enumerable, champX, enumerable, champY);
        }
        protected void InitSerie(string name)
        {
            Series Cpu = new System.Windows.Forms.DataVisualization.Charting.Series();

            // Cpu.BorderColor = m_CpuBorderColor;
            Cpu.Name = name.Remove(0, 2);
            Cpu.BorderWidth = 2;
            Cpu.ChartArea = "Default";
            Cpu.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            Cpu.Legend = "Default";
            // Cpu.ShadowColor = m_CpuShadowColor;
            Cpu.ShadowOffset = 2;
            Cpu.ToolTip = "#SERIESNAME: X=#VALX{T} Y=#VAL";
          // Cpu.AxisLabel = "#VALX{T}";
            _SeriesList.Add(name, Cpu);
            this.Chart1.Series.Add(Cpu);
        }
        protected void InitSeries()
        {
            InitSerie("S+CPU01:Idle Time%");
            _plotsqlElement.GetSerie(Chart1.Series["S+CPU01:Idle Time%"]);
            DataTable reader = _plotElement.GetCPU_ALLReader();
            InitSerie("test",reader.DefaultView,"x","y");
            
           /* InitSerie("test2");
            DataTable dt = _plotElement.GetCPU_ALLReader2();
            Chart1.Series["test2"].Points.DataBindXY(dt.DefaultView, "zzzz", dt.DefaultView, "Waittime");
            */
            /*RemoveSerie("test");
            InitSerie("test");
           // DataTable reader = _plotElement.GetCPU_ALLReader();
            Chart1.Series["test"].Points.DataBindXY(reader.DefaultView, "zzzz", reader.DefaultView, "Usertime");
            */
        }
        public void AddSerie(string name)
        {
            if (!_SeriesList.ContainsKey(name))
            {
                InitSerie(name);
            }
           // _plotsqlElement.GetSerie(Chart1.Series[_SeriesList[name].Name],);

            _plotsqlElement.GetSerie(_SeriesList[name],name);
        }
        public void RemoveSerie(string name)
        {
            if (_SeriesList.ContainsKey(name))
            {
                Chart1.Series[_SeriesList[name].Name].Dispose();

                this.Chart1.Series.Remove(_SeriesList[name]);
                _SeriesList.Remove(name);
            }
        }
        public void InitChar()
        {
            try
            {
                // Create a Chart
                Chart1 = new Chart();

                // Create Chart Area
                ChartArea chartArea1 = new ChartArea();
                InitChartArea(chartArea1);

                // Add Chart Area to the Chart
                Chart1.ChartAreas.Add(chartArea1);
                //InitSeries();
                // Set chart control location
                Chart1.Location = new System.Drawing.Point(16, 48);

                // Set Chart control size
                Chart1.Size = new System.Drawing.Size(360, 260);
                Chart1.Dock = DockStyle.Fill;
                Chart1.ContextMenuStrip = this.contextMenuStrip1;

                // Add chart control to the form
                this.Controls.AddRange(new System.Windows.Forms.Control[] { this.Chart1 });
                if (m_AddLegend)
                {
                    SetLegends();
                }


            }
            catch (System.Exception ex)
            {

            }
        }

        public void afficherLégendeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_AddLegend)
            {
                this.Chart1.Legends.Remove(legend1);
                this.afficherLégendeToolStripMenuItem.Checked = false;
                this.afficherLégendeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Unchecked;

            }
            else
            {
                SetLegends();
                this.afficherLégendeToolStripMenuItem.Checked = true;
                this.afficherLégendeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;

            }
            m_AddLegend = !m_AddLegend;
        }

        public void imprimerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tireguit.HelpPrint.PrintChart printchart = new Tireguit.HelpPrint.PrintChart();
            printchart.Print(Chart1,
                "Utilisation des ressources",
                "Tireguit Nmon Analyzer: (c)HT Consulting",
                StartDate);
        }

        public void supprimerTousLesGraphsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string[] keys = _SeriesList.Keys.ToArray();
            foreach (var key in keys)
            {
                RemoveSerie(key);
            }
        }

       


    }
}
